﻿using System.Collections.Generic;
using TYBase;

namespace TYPLC {
    public class PLCCreator {
        private readonly TagConfigExBase tagConfigEx;
        private List<GroupPara> listGroup;

        public PLCCreator(TagConfigExBase tagConfigEx) {
            this.tagConfigEx = tagConfigEx;
        }

        public List<GroupPara> GroupParas() {
            if (tagConfigEx == null) {
                listGroup = new List<GroupPara>();
            }
            else {
                if (listGroup == null)
                    listGroup = tagConfigEx.GetGroup();
            }

            return listGroup;
        }



        public bool InitPLC(IPLCConnector plc, DelegateOnDataChange OnDataChanged, ref string error) {
            Log.I(" InitPLC start ");
            if (tagConfigEx == null) {
                return false;
            }


            GroupParas();

            plc.OnDataChange += OnDataChanged;


            foreach (var item in listGroup) {
                if (!plc.AddGroup(item)) {
                    error = $"初始化PLC {item.GroupName} 失败!";
                    Log.I($"{error}");
                    return false;
                }
            }

            if (!plc.Connect()) {
                error = "PLC连接失败!";
                return false;
            }

            plc.Start();
            return true;
        }
    }
}